package com.openfire.client.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.ConnectionConfiguration.SecurityMode;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.receipts.DeliveryReceiptManager;
import org.jivesoftware.smackx.receipts.DeliveryReceiptManager.AutoReceiptMode;

/**
 * openfire client
 * 
 */
public class App3_dev_2 {
	public static void main(String[] args) throws InterruptedException {

		// 202.104.147.108 开发环境
		String from = "fmhdkf", to = "automess", serviceName = "202.104.147.108", host = "172.17.210.108";

		XMPPTCPConnectionConfiguration configuration = XMPPTCPConnectionConfiguration
				.builder().setHost(serviceName).setPort(5222)
				.setServiceName(serviceName)
				.setSecurityMode(SecurityMode.disabled)
				.setUsernameAndPassword(from, from).setDebuggerEnabled(true)
				.build();
		AbstractXMPPConnection connection = new XMPPTCPConnection(configuration);
		try {
			connection.connect();
			connection.login();

			// 自动处理回执消息
			DeliveryReceiptManager.getInstanceFor(connection)
					.setAutoReceiptMode(AutoReceiptMode.always);

			System.out.println(from + " login ok!");
			ChatManager chatManager = ChatManager.getInstanceFor(connection);
			chatManager.addChatListener(new ChatManagerListener() {
				@Override
				public void chatCreated(Chat chat, boolean createdLocally) {
					chat.addMessageListener(new ChatMessageListener() {

						@Override
						public void processMessage(Chat chat, Message message) {
							String body = message.getBody();
							if (body != null) {
								System.out.println("接收到消息: " + body);
							}
						}
					});
				}
			});
			Chat chat = chatManager.createChat(to + "@" + serviceName);
			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));
			while (true) {
				String content = br.readLine();
				if ("exit".equals(content)) {
					break;
				}
				Message message = new Message(to, Message.Type.chat);
				message.setBody(content);
				// message.setFrom(from + "@" + serviceName + "/smack");
				// message.setTo(to + "@" + serviceName + "/smack");

				chat.sendMessage(message);
			}
		} catch (XMPPException e) {
			e.printStackTrace();
		} catch (SmackException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		System.out.println("end!");
	}
}
